import { IPhones } from '../typings';
import{ useEffect, useState } from 'react';
import { getPhones } from '../services';
import { useDispatch } from 'react-redux';
import { Dispatch } from 'redux';
import { SET_PHONE_LIST } from '../store/actionTypes';

/**
 * @description 该自定义hook完成数据请求和保存state操作
 * @returns 请求数据后的phoneList数组
 */
function usePhoneList(): IPhones[] {
  //初始化一个phoneList = []
  const [phoneList, setPhoneList] = useState<IPhones[]>([]);

  const dispatch: Dispatch = useDispatch();

  //使用副作用钩子去请求数据
  useEffect(() => {
    //请求
    getPhones<IPhones[]>()
      .then((data) => {
        //保存state仓库
        dispatch({
          type: SET_PHONE_LIST,
          payload: data
        });

      //保存data到phoneList数组里
        setPhoneList(data);
      })
      .catch(e => console.log(e));
    
   }, [dispatch]);

   //返回请求数据后的phoneList数组
   return phoneList;
}

export default usePhoneList;